package cn.congine.wizarpos.mall.weChat;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.congine.wizarpos.mall.weChat.bussiness.WechartCoreService;
import cn.congine.wizarpos.mall.weChat.util.SignUtil;

@Controller
@RequestMapping(value = "/wechat")
public class WeChatction {

	private static Logger log = LoggerFactory.getLogger(WeChatction.class);

	public static final String ServiceURL = "/entry";
	public static final String CreateMenu = "/createMenu";

	@Autowired
	private WechartCoreService wechartCoreService;
	
	@RequestMapping(value = ServiceURL)
	public void wechatEntryPoint(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		
		PrintWriter out = response.getWriter();
		if (!StringUtils.isEmpty(echostr) && SignUtil.checkSignature(signature, timestamp, nonce)) {
			// 微信配置接入测试，通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
			out.print(echostr);
		} else { 
			// 一般消息处理
			out.print("");
			out.print("success");
			try {
				String respMessage = wechartCoreService.processRequest(request, response);
				log.debug(respMessage);
				out.print(respMessage);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		out.close();
		out = null;
	}

	@RequestMapping(value = CreateMenu)
	public void CreateMenu() {
	}

}

